<?php
declare(strict_types=1);

namespace App\Service\Pushapp;
use Exception;
use Hyperf\Guzzle\ClientFactory;
use Psr\Log\LoggerInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
/**
 * oppo推送
 */
class OpposService
{
	protected ClientFactory $clientFactory;

    protected LoggerInterface $logger;

    protected $redis;
    /**
     * [$api 国内生产环境-推送消息-api]
     * @var string
     */
    private $api = 'https://api.push.oppomobile.com/';
    /**
     * [$ret_api 国内生产环境-反馈信息-api]
     * @var string
     */
    private $ret_api = 'https://feedback.push.oppomobile.com/';
    /**
     * [$device_api 标签管理-api]
     * @var string
     */
    private $device_api = 'https://api-device.push.heytapmobi.com/';

    /**
     * @var string
     */
    private $token_cache_key = 'newxhqandroidpush:token:oppo-tocken';

    /**
     * @var string
     */
    private $oppo_lock_key = 'newxhqandroidpush:oppo-lock';

    /**
     * @var mixed
     */
    private $app_key = '';

    /**
     * @var mixed
     */
    private $master_secret = '';
   

    public function __construct(ClientFactory $clientFactory,LoggerFactory $loggerFactory)
    {
        $this->clientFactory = $clientFactory;
        $this->logger = $loggerFactory->get('log', 'default');
        $container = ApplicationContext::getContainer();
        $this->redis = $container->get(\Hyperf\Redis\Redis::class);
        $config = config('xhqparams.oppo', []);
        $this->app_key =  $config['appKey'];
        $this->master_secret =  $config['masterSecret'];
    }
    /**
     * [sPush 发送单条推送]
     * @param  array  $push_data [description]
     * @param  string $reg_id    [description]
     * @return [type]            [description]
     */
    public function sPush(array $push_data, string $reg_id)
    {
        
        $notification = [];
        $notification['title'] = $push_data['title'];
        $notification['content'] = $push_data['content'];
        if(isset($push_data['sub_title']) && !empty($push_data['sub_title'])){
            $notification['sub_title'] = $push_data['sub_title'];
        }
        if (isset($push_data['extra']) && !empty($push_data['extra'])) {
            $notification['action_parameters']['PUSH_EXTRA_KEY'] =json_encode($push_data['extra']);
        }
        $notification['click_action_type'] = 4;

        $notification['channel_id'] = isset($push_data['extra']) && !empty($push_data['extra']['tag']) && $push_data['extra']['tag']=='myq_push'?'privatepushNotification':'compushNotification';
        $notification['click_action_activity'] = 'com.nursegroup.recruitment.push.oppo.OppoPushActivity';

        $message1 = [];
        $message1['target_type'] = 2;
        $message1['target_value'] = $reg_id;
        $message1['notification'] = $notification;

        $data = [
            'auth_token' => $this->getTocken(),
            'message' => json_encode($message1),
        ];
        $options = [
            'base_uri' => $this->api,
            'timeout'  => 3.0,
        ];
        $post_guz = [
            'form_params' => $data
        ];
        $resp = $this->clientFactory->create($options)->request('post','server/v1/message/notification/unicast',$post_guz);
        $result_body = $resp->getBody()->getContents();
        $res = json_decode($result_body,true);
        if(isset($res['code']) && $res['code']==0){
            return ['status'=>1,'data'=>$res];
        }elseif(isset($res['code']) && $res['code']==33){
            //当日超过限制不再通知
            return ['status'=>0,'data'=>$res];
        }else{
            return ['status'=>0,'data'=>$res];
        }
    }


    /**
     * 获取鉴权时间搓
     * @return float
     */
    private function getTimeStamp(): float
    {
        list($msec, $sec) = explode(' ', microtime());
        
        return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    }

    /**
     * [getTocken 获取token]
     * @return string
     */
    public function getTocken(): string
    {
        if ($this->redis->exists($this->token_cache_key)) {
            return $this->redis->get($this->token_cache_key);
        }
       
        $timestamp = $this->getTimeStamp();
        $sign = hash('sha256',$this->app_key.$timestamp.$this->master_secret);
        $param = [
            'app_key'=>$this->app_key,
            'sign'=>$sign,
            'timestamp'=>$timestamp
        ];
        $options = [
            'base_uri' => $this->api,
            'timeout'  => 6.0,
        ];
        $post_guz = [
            'form_params' => $param
        ];
        $resp = $this->clientFactory->create($options)->request('post','server/v1/auth',$post_guz);
        $result_body = $resp->getBody()->getContents();
        $res = json_decode($result_body,true);
        if(isset($res) && isset($res['data']['auth_token'])){
            $this->redis->set($this->token_cache_key,$res['data']['auth_token'],7200);
        }
        return isset($res['data']['auth_token'])?$res['data']['auth_token']:'';
    }
}